package com.pilot.game.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.pilot.game.domain.Agency;
import com.pilot.game.service.AgencyService;
import com.pilot.game.service.CustomerService;
import com.pilot.game.web.rest.errors.BadRequestAlertException;
import com.pilot.game.web.rest.util.HeaderUtil;
import com.pilot.game.web.rest.util.PaginationUtil;
import com.pilot.game.web.rest.vm.CommonResponse;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Agency.
 */
@RestController
@RequestMapping("/api")
public class AgencyResource {

    private final Logger log = LoggerFactory.getLogger(AgencyResource.class);

    private static final String ENTITY_NAME = "agency";

    private final AgencyService agencyService;
    private final CustomerService customerService;

    public AgencyResource(AgencyService agencyService, CustomerService customerService) {
        this.agencyService = agencyService;
        this.customerService = customerService;
    }

    /**
     * POST  /agencies : Create a new agency.
     *
     * @param agency the agency to create
     * @return the ResponseEntity with status 201 (Created) and with body the new agency, or with status 400 (Bad Request) if the agency has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/agencies")
    @Timed
    public ResponseEntity<Agency> createAgency(@Valid @RequestBody Agency agency) throws URISyntaxException {
        log.debug("REST request to save Agency : {}", agency);
        if (agency.getId() != null) {
            throw new BadRequestAlertException("A new agency cannot already have an ID", ENTITY_NAME, "idexists");
        }

        if (agencyService.findByName(agency.getAccountName()) != null) {
            throw new BadRequestAlertException("代理商名已存在", ENTITY_NAME, "idexists");
        }

        Agency father = agencyService.findByName(agency.getFather());
        int sumAgencyByFather = agencyService.findSumAgencyByFather(father.getAccountName());
        int countCustomer = customerService.findCountByAgency(father.getAccountName());
        if ((father.getLimit() - sumAgencyByFather - countCustomer) < agency.getLimit()) {
            throw new BadRequestAlertException("你可创建客户数量不足", ENTITY_NAME, "idexists");
        }

        Agency result = agencyService.save(agency);
        return ResponseEntity.created(new URI("/api/agencies/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * POST  /agencies／login : agencies login
     *
     * @param agency the customer to login
     * @return the ResponseEntity with status 201 (Created) and with body the new customer, or with status 400 (Bad Request) if the customer has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/agencies/login")
    @Timed
    public ResponseEntity<Agency> agencyLogin(@RequestBody Agency agency) throws URISyntaxException {
        log.debug("REST request to login agency : {}", agency);
        Agency result = agencyService.findByNameAndPwd(agency.getAccountName(), agency.getPassword());
        if(result == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        if(result.getDeadline().isBefore(LocalDate.now())){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.ok(result);
    }


    /**
     * PUT  /agencies : Updates an existing agency.
     *
     * @param agency the agency to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated agency,
     * or with status 400 (Bad Request) if the agency is not valid,
     * or with status 500 (Internal Server Error) if the agency couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/agencies")
    @Timed
    public ResponseEntity<Agency> updateAgency(@Valid @RequestBody Agency agency) throws URISyntaxException {
        log.debug("REST request to update Agency : {}", agency);
        if (agency.getId() == null) {
            return createAgency(agency);
        }
        Agency father = agencyService.findByName(agency.getFather());
        int sumAgencyByFather = agencyService.findSumAgencyByFather(father.getAccountName());
        int countCustomer = customerService.findCountByAgency(father.getAccountName());
        if ((father.getLimit() - sumAgencyByFather - countCustomer) < agency.getLimit()) {
            throw new BadRequestAlertException("你可创建客户数量不足", ENTITY_NAME, "idexists");
        }

        Agency result = agencyService.save(agency);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, agency.getId().toString()))
            .body(result);
    }

    /**
     * GET  /agencies : get all the agencies.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of agencies in body
     */
    @GetMapping("/agencies")
    @Timed
    public ResponseEntity<List<Agency>> getAllAgencies(@ApiParam Pageable pageable, @ApiParam String father) {
        log.debug("REST request to get a page of Agencies");
        Agency agency = new Agency();
        agency.setFather(father);
        Example<Agency> example = Example.of(agency);
        Page<Agency> page = agencyService.findAll(example,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/agencies");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /agencies/:id : get the "id" agency.
     *
     * @param id the id of the agency to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the agency, or with status 404 (Not Found)
     */
    @GetMapping("/agencies/{id}")
    @Timed
    public ResponseEntity<Agency> getAgency(@PathVariable Long id) {
        log.debug("REST request to get Agency : {}", id);
        Agency agency = agencyService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(agency));
    }

    /**
     * DELETE  /agencies/:id : delete the "id" agency.
     *
     * @param id the id of the agency to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/agencies/{id}")
    @Timed
    public ResponseEntity<CommonResponse> deleteAgency(@PathVariable Long id) {
        log.debug("REST request to delete Agency : {}", id);
        agencyService.delete(id);
        return new ResponseEntity<>(new CommonResponse("SUCCESS", true), HttpStatus.OK);
    }
}
